<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\wechat\controller;

use app\wechat\service\FansService;
use app\wechat\service\TagsService;
use controller\BasicAdmin;
use service\DataService;
use service\LogService;
use service\ToolsService;
use service\WechatService;
use think\Db;

/**
 * 微信粉丝管理
 * Class Fans
 * @package app\wechat\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/03/27 14:43
 */
class Factory extends BasicAdmin
{

    /**
     * 定义当前默认数据表
     * @var string
     */
    public $table = 'store_shops';

    /**
     * 显示粉丝列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function index()
    {
        $this->title = '商家列表';
        $get = $this->request->get();

        $db = Db::table($this->table);

        if  (isset($get['agent']) && $get['agent'] !== '' ){
            $db->where('admininfo','=',$get['agent']);
        }

        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }

        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->where('name', 'like',"%{$get['nickname']}%");
        }
        if (isset($get['shop_name']) && $get['shop_name'] !== '') {
            $db->where('shop_name', 'like',"%{$get['shop_name']}%");
        }
        if (isset($get['phone']) && $get['phone'] !== '') {
            $db->where('phone', 'like',"%{$get['phone']}%");
        }
        if (isset($get['member_level']) && $get['member_level'] !== '') {
            $db->where('member_level', '=',$get['member_level']);
        }

        return parent::_list($db->order('create_at desc'));
    }




    public function _index_data_filter( &$data )
    {
    }

    public function useradd()
    {
        if(request()->isPost()){
            $post = request()->post();
            if($post['admininfo']!='')
            {
                $agent = Db::name('agent')->where('username',$post['admininfo'])->find();
                if(!$agent)
                {
                    $this->error('您输入的代理不存在!');
                }else
                {

                    $post['admin'] = $agent['id'];
                }
            }
        }
        $shop = Db::name('store_shops')->order('id desc')->find();
        $exsit = Db::name('sys_lettery')->where("shop_id",$shop['id'])->find();
        if (!$exsit){
            $insertdata1 = [
                'title' =>'一级功勋',
                'create_at' => date("Y-m-d H:i:s",time()),
                'sort'  => 1,
                'shuliang'  => 5,
                'shop_id'   => $shop['id']
            ];
            $insertdata2 = [
                'title' =>'二级功勋',
                'create_at' => date("Y-m-d H:i:s",time()),
                'sort'  => 2,
                'shuliang'  => 10,
                'shop_id'   => $shop['id']
            ];
            $insertdata3 = [
                'title' =>'三级功勋',
                'create_at' => date("Y-m-d H:i:s",time()),
                'sort'  => 3,
                'shuliang'  => 15,
                'shop_id'   => $shop['id']
            ];
            $insertdata4 = [
                'title' =>'四级功勋',
                'create_at' => date("Y-m-d H:i:s",time()),
                'sort'  => 4,
                'shuliang'  => 20,
                'shop_id'   => $shop['id']
            ];
            Db::name("sys_lettery")->insert($insertdata1);
            Db::name("sys_lettery")->insert($insertdata2);
            Db::name("sys_lettery")->insert($insertdata3);
            Db::name("sys_lettery")->insert($insertdata4);
        }
        $levellist = Db::name('agent')->where('status',1)->select();
        $areaList = Db::name('sys_address')->where(['area_parent_id'=>0])->select();
        $areaifno = Db::name('sys_address')->where('area_parent_id','>',0)->select();
//        dump($levellist);
        $this->assign('level',$levellist);
        $this->assign('areaList', $areaList);
        $this->assign('areaifno', $areaifno);
        return $this->_form($this->table, 'user_add');
    }


    public function useredit()
    {
        if(request()->isPost()){
            $post = request()->post();
            if($post['admininfo']!='')
            {
                if(!Db::name('agent')->where('username',$post['admininfo'])->find())
                {
                    $this->error('您输入的代理不存在!');
                }
            }
          

        }


        $levellist = Db::name('agent')->where('status',1)->select();
    	$areaList = Db::name('sys_address')->where(['area_parent_id'=>0])->select();
        $areaifno = Db::name('sys_address')->where('area_parent_id','>',0)->select();
        $type = 'edit';
        $this->assign('type',$type);
        $this->assign('level',$levellist);
        $this->assign('areaList', $areaList);
        $this->assign('areaifno', $areaifno);
        return $this->_form($this->table, 'user_add');
    }

    //查看团队
    public function team(){
        $this->title = '用户中心';
        $get = $this->request->get();
        $db = Db::name('store_member');
        if (isset($get['id']) && $get['id'] != '') {
            $where['shop_id'] = $get['id'];
            $db->where($where)->select();
        }


        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        if (isset($get['create_at']) && $get['create_at'] != ''){
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $num = Db::name('store_member');
            $num->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $count['time'] = 2;
            $count['vip'] = $num->where('member_level',2)->count();
            $count['yubei'] = $num->where('member_level',1)->count();
        }else{
            $count['time'] = 3;
            $count['vip'] = Db::name('store_member')->where('member_level',2)->count();
            $count['yubei'] = Db::name('store_member')->where('member_level',1)->count();
        }
        $this->assign('count',$count);
        if (isset($get['member_level']) && $get['member_level'] !== '') {
            $db->where('member_level', '=',$get['member_level']);
        }


        foreach (['phone', 'member_level','creat_at'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db->order('id desc'));
    }

    public function carid(){
        $this->title = "历史车牌";
        $get = input('get.');
        $db = Db::name('store_member_carid')
            ->alias('a')
            ->join('store_member b','a.uid = b.id')
            ->field('b.truename,a.id,a.sheng,a.carid,a.addtime');
//        dump($db);
//        die();
        if (isset($get['id']) && $get['id'] !== '' ){
            $where['uid'] = $get['id'];
            $db->where($where);
        }

        return parent::_list($db->order('id desc'));
    }

    public function pass(){
        if ($this->request->isGet()) {
        $this->assign('verify', false);
        $this->table = 'store_shops';
        return $this->_form($this->table, 'pass');
    }
        $post = $this->request->post();
        if ($post['password'] !== $post['repassword']) {
            $this->error('两次输入的密码不一致！');
        }
        $data = ['id' => $post['id'], 'password' => $post['password']];
        if (DataService::save($this->table, $data, 'id')) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    //查看下级
    public function lower(){
        $this->title = '用户中心';
        $get = $this->request->get();
        $db = Db::name('store_member');
        if (isset($get['id']) && $get['id'] != '') {
            $where['first_leader'] = $get['id'];
            $db->where($where);
        }


        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        foreach (['phone', 'member_level'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db->order('id desc'));
    }


    public function user_balance()
    {
        if($this->request->post()){
            $data = $this->request->post();
            if($data['member_id']){
                $content_str = '';
                if($data['recharge_type'] ==1){
                    $content_str = "后台减少用户:{$data['member_id']},金额:{$data['account_money']}";
                    $data['account_money'] = '-'.$data['account_money'];
                }else{
                    $content_str = "后台增加用户:{$data['member_id']},金额:{$data['account_money']}";
                    $data['account_money'] = $data['account_money'];
                }
                Db::startTrans();
                $res = mlog($data['member_id'],'account_money',$data['account_money'],$content_str,'20');
                if(check_arr($res)){
                    Db::commit();
                    return $this->success('操作成功');
                }else{
                    Db::rollback();
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('账户不存在！');
            }
        }
        return view();
    }

	

    public function cityList()
    {
        $info = $this->request->post();
        if(!empty($info['provinceid'])){
            $goodsInfo=Db::name('sys_address')->where(['area_parent_id'=>$info['provinceid']])->select();
            return $this->result($goodsInfo,200,'成功','');
        }
        return $this->renderError('缺少参数');
    }

    public  function districtList(){
        $info = $this->request->post();
        if(!empty($info['cityid'])){
            $goodsInfo=Db::name('sys_address')->where(['area_parent_id'=>$info['cityid']])->select();
            return $this->result($goodsInfo,200,'成功','');
        }
        return $this->renderError('缺少参数');
    }
    
    public function user_credit()
    {
        if($this->request->post()){
            $data = $this->request->post();
            if($data['member_id']){
                Db::startTrans();
                $res = Db::name('store_shops')->where(['id'=>$data['member_id']])->update(['credit'=>$data['credit']]);
                if(($res)){
                    Db::commit();
                    return $this->success('操作成功');
                }else{
                    Db::rollback();
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('账户不存在！');
            }
        }
        return view();
    }



    /**
     * 设置黑名单
     */
    public function backadd()
    {

        try {
            $is_disable = Db::name('store_shops')->where('id', input('param.id'))->value('is_disable');
            $is_disable = $is_disable == 1 ? -1 : 1;
            Db::name('store_shops')->where('id', input('param.id'))->setField('is_disable', $is_disable);
        } catch (\Exception $e) {
            $this->error("操作失败，请稍候再试！");
        }
        $this->success('操作成功！', '');
    }

}
